﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeamWork_Server.HTTP;
using System.IO;

namespace TeamWork_Server
{
    class Program
    {
        static string GetData(string p)
        {
            string[] ff = File.ReadAllLines(@".\config.ini");
            foreach (string f in ff)
            {
                if(f.Contains(p))
                    return f.Replace(p + "=", "").Replace('"', '\0').Trim('\0');
            }
            return "";
        }

        static void Main(string[] args)
        {
            Log.Initialize("TeamWork Server.txt", LogLevel.All, false);
            Subscriptions:
            if (File.Exists(@".\subscriptions.dg"))
            {
                Subscriptions.Subscriptions.Initialize(@".\subscriptions.dg", false);
                Log.Info("Subscriptions file found! Initialized Subscriptions data grouper.");
            }
            else
            {
                Log.Info("Subscriptions file not found! Creating a new one and retyring...");
                Subscriptions.Subscriptions.Initialize(@".\subscriptions.dg");
                Log.Info("Subscription storage has been created. Press any key to continue...");
                Console.ReadKey();
                Console.Clear();
                goto Subscriptions;
            }
            CommandsFactory.Initialize();
            Console.Title = "TeamWork Server v0.2b";
            //Console.WriteLine("Please assing to 'net_external_ip' a value:");
            string ip = GetData("ServerExternalIP");//Console.ReadLine();
            CommandsFactory.Variables["net_external_ip"] = (ip=="localhost" ? "127.0.0.1" : ip);
            Log.Debug("Using IP: " + ip);
            long rp = long.Parse(GetData("RconPassword"));
            Log.Debug("Using RCON Password: " + rp.ToString());
            //Console.WriteLine("Assing a password for the RCON tool (numbers only):");
            //long rp = long.Parse(Console.ReadLine());
            //Console.Clear();
            TWServerConfiguration c = new TWServerConfiguration(@GetData("StartupProject"));
            CommandsFactory.Variables["admin_master_key"] = long.Parse(c.MasterKey);
            FileTransfer ft = new FileTransfer(ip, 8080, c);
            ft.Start();
            RConHandler rch = new RConHandler(rp);
            rch.Start();
            SubscriptionService ss = new SubscriptionService();
            ss.Start();
            ChatService cs = new ChatService();
            cs.Start();
            while (true)
            {
                Log.WriteAway();
            }
        }
    }
}
